#include <QDebug>

#include "cvusermanager.h"
#include "model/cvprofile.h"

CVUserManager::CVUserManager()
{

}

void CVUserManager::validating(const QString &username, const QString &password, const QString &network)
{
    QByteArray bytes;
    bytes.begin();
    bytes.append("username=");
    bytes.append(username);
    bytes.append("&");
    bytes.append("password=");
    bytes.append(password);
    bytes.end();
    CVHttp *http = new CVHttp(CVUtil::getBaseUrl("cvauth.authenticate", network), bytes);
    connect(http, SIGNAL(finished(QScriptValue,QString)), this, SLOT(handValidate(QScriptValue,QString)));
    connect(http, SIGNAL(handleError(QNetworkReply::NetworkError)), this, SLOT(handError(QNetworkReply::NetworkError)));
}

void CVUserManager::getLoggedUser()
{
    CVSession *session = CVSession::get();
    QString sessionId = session->getSessionId();
    if (!sessionId.isEmpty())
    {
        QString userId = session->getUserId();
        if (!userId.isEmpty())
        {
            QUrl requestUrl = CVUtil::getBaseUrl("profile.get_profile_for_user", session->getCurrentNetwork()->getUrl());
            requestUrl.addQueryItem("user_id", userId);
            CVHttp *http = new CVHttp(requestUrl);
            connect(http, SIGNAL(finished(QScriptValue,QString)), this, SLOT(parseUserData(QScriptValue,QString)));
        }
        else
        {
            qDebug() << "[CVUserManager::getLoggedUser] Can not find user id";
        }
    }
    else
    {
        qDebug() << "[CVUserManager::getLoggedUser] Session id is empty";
    }
}

void CVUserManager::handValidate(QScriptValue value, const QString &msg)
{
    QScriptEngine engine;
    if (!value.isNull() && !value.isError() && msg.isEmpty())
    {
        qDebug() << "session id: " << value.toString();
        // set session id
        emit validated(true, value.toString(), QNetworkReply::NoError);
    }
    else
    {
        qDebug()<<engine.uncaughtException().toString();
        qDebug()<<engine.uncaughtExceptionBacktrace().join("\n");
        emit validated(false, msg, QNetworkReply::NoError);
    }
}

void CVUserManager::handError(QNetworkReply::NetworkError error)
{
    emit validated(false, "NetworkError", error);
}

void CVUserManager::parseUserData(QScriptValue json, const QString &msg)
{
    if (!json.isNull() && !json.isError())
    {
        // It seems that the result is array of object
        // just gets the first one
        QScriptValue userData = json.property("0");

        CVUser *cvuser = new CVUser();
        CVProfile *cvprofile = new CVProfile();
        cvuser->setId(userData.property("id").toString().toInt());
        cvuser->setName(userData.property("name").toString());
        cvuser->setFirstName(userData.property("firstname").toString());
        cvuser->setLastName(userData.property("lastname").toString());
//        qDebug() << "icon: " << userData.property("icon").toString();
//        qDebug() << "id: " << userData.property("id").toString();
        QString userIcon = userData.property("icon").toString();
        userIcon = userIcon.replace("large", "small");
        cvuser->setIcon(userIcon);
        cvuser->setIsGuset((userData.property("guest_member").toInt32() != 0));
        cvuser->setTimeCreated(userData.property("time_created").toString());
        cvuser->setTimeUpdated(userData.property("time_updated").toString());

        cvprofile->setDescription(userData.property("description").toString());
        cvprofile->setBriefDescription(userData.property("briefdescription").toString());
        cvprofile->setDepartment(userData.property("department").toString());
        cvprofile->setContactEmail(userData.property("contactemail").toString());
        cvprofile->setAolimid(userData.property("aolimid").toString());
        cvprofile->setCompanyName(userData.property("companyname").toString());
        cvprofile->setCountry(userData.property("country").toString());
        cvprofile->setLocation(userData.property("location").toString());
        cvprofile->setMobile(userData.property("mobile").toString());
        cvprofile->setMobileEmail(userData.property("mobileemail").toString());
        cvprofile->setMsnId(userData.property("msnid").toString());
        cvprofile->setSkypeId(userData.property("skypeid").toString());
        cvprofile->setPhone(userData.property("phone").toString());
        cvprofile->setYahooId(userData.property("yahooid").toString());

        cvuser->setProfile(cvprofile);
        emit handleUser(cvuser, "");
    }
    else
    {
        emit handleUser(NULL, msg);
    }
}
